﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml.Linq;
using InterpriseSuiteEcommerceCommon.Extensions;
using Interprise.Framework.Customer.DatasetGateway;
using InterpriseSuiteEcommerceCommon.DTO;
using InterpriseSuiteEcommerceCommon.InterpriseIntegration;
using InterpriseSuiteEcommerceCommon.Tool;

namespace InterpriseSuiteEcommerceCommon.InterpriseIntegration
{
    public class MobileCheckOutPaymentPageLiteralRenderer : IShoppingCartHTMLLiteralRenderer
    {
        public void Render(InterpriseShoppingCart cart, ref StringBuilder output)
        {
            bool showPicsInCart = AppLogic.AppConfigBool("ShowPicsInCart");
            bool showLinkBack = AppLogic.AppConfigBool("LinkToProductPageInCart");
            bool hideUnitMeasure = AppLogic.AppConfigBool("HideUnitMeasure");
            bool showShipDateInCart = AppLogic.AppConfigBool("ShowShipDateInCart");
            bool showStockHints = AppLogic.AppConfigBool("ShowStockHints");
            bool varEnabled = AppLogic.AppConfigBool("VAT.Enabled");

            var root = new XElement(DomainConstants.XML_ROOT_NAME);
            root.Add(new XElement("SKINID", cart.SkinID));
            root.Add(new XElement("CLICK_HERE_SUB_TEXT", AppLogic.GetString("checkoutcard.aspx.1", cart.SkinID, cart.ThisCustomer.LocaleSetting)));
            root.Add(new XElement("CLICK_HERE_TEXT", AppLogic.GetString("checkoutcard.aspx.2", cart.SkinID, cart.ThisCustomer.LocaleSetting)));

            string couponCode = string.Empty;
            bool hasCoupon = cart.HasCoupon(ref couponCode);
            if (hasCoupon)
            {
                root.Add(new XElement("HASCOUPON", hasCoupon));
                root.Add(new XElement("COUPON_HEADER_TEXT", AppLogic.GetString("mobile.shoppingcart.aspx.19", cart.SkinID, cart.ThisCustomer.LocaleSetting)));
                root.Add(new XElement("COUPON_TEXT", AppLogic.GetString("checkoutshipping.aspx.15", cart.SkinID, cart.ThisCustomer.LocaleSetting)));
                root.Add(new XElement("COUPON_VALUE", couponCode.ToHtmlEncode()));
            }

            root.Add(new XElement("CHECKOUTSHIPPING_HEADER_TEXT", AppLogic.GetString("mobile.checkoutshipping.aspx.13", cart.SkinID, cart.ThisCustomer.LocaleSetting)));
            foreach (CartItem item in cart.CartItems)
            {
                var lineItemRow = item.AssociatedLineItemRow;

                var xmlcartItem = new XElement("CART_ITEMS");
                root.Add(xmlcartItem);

                string producthref = InterpriseSuiteEcommerceCommon.InterpriseHelper.MakeItemLink((string)lineItemRow["ItemCode"]);
                string productName = !string.IsNullOrEmpty(lineItemRow["ItemDescription"].ToString()) ? lineItemRow["ItemDescription"].ToString().ToHtmlEncode() : lineItemRow["ItemName"].ToString().ToHtmlEncode();

                xmlcartItem.Add(new XElement("SHOWPICSINCART", showPicsInCart));
                xmlcartItem.Add(new XElement("SHOWSHIPDATEINCART", showShipDateInCart));
                xmlcartItem.Add(new XElement("SHOW_LINKBACK", showLinkBack));
                xmlcartItem.Add(new XElement("CART_ITEMCODE", lineItemRow["ItemCode"].ToString()));
                xmlcartItem.Add(new XElement("CART_ITEM_ID", lineItemRow["counter"].ToString()));
                xmlcartItem.Add(new XElement("PRODUCTLINKNAME", productName));

                if (showPicsInCart)
                {
                    var img = ProductImage.Locate("product", item.ItemCounter, "icon");
                    if (null != img)
                    {
                        string seTitle = "";
                        string seAltText = "";
                        string itemCode = itemCode = InterpriseHelper.GetInventoryItemCode(item.ItemCounter);
                        AppLogic.GetSEImageAttributes(itemCode, "ICON", AppLogic.GetLanguageCode(cart.ThisCustomer.LocaleSetting), ref seTitle, ref seAltText);

                        xmlcartItem.Add(new XElement("PRODUCTIMAGEPATH", img.src));
                        xmlcartItem.Add(new XElement("PRODUCTIMAGETITLE", seTitle));
                        xmlcartItem.Add(new XElement("PRODUCTIMAGEALT", seAltText));
                    }
                }

                switch ((string)lineItemRow["ItemType"])
                {
                    case Interprise.Framework.Base.Shared.Const.ITEM_TYPE_MATRIX_GROUP:

                    #region "ITEM_TYPE_MATRIX_ITEM"
                    case Interprise.Framework.Base.Shared.Const.ITEM_TYPE_MATRIX_ITEM:
                        xmlcartItem.Add(new XElement("ITEM_TYPE", "ITEM_TYPE_MATRIX_ITEM"));
                        if (showLinkBack)
                        {
                            using (var con = DB.NewSqlConnection())
                            {
                                con.Open();
                                using (var reader = DB.GetRSFormat(con, "SELECT ItemCode FROM InventoryMatrixItem with (NOLOCK) WHERE MatrixItemCode = {0}", DB.SQuote(lineItemRow.ItemCode)))
                                {
                                    if (reader.Read())
                                    {
                                        xmlcartItem.Add(new XElement("PRODUCT_HREF", InterpriseSuiteEcommerceCommon.InterpriseHelper.MakeItemLink(DB.RSField(reader, "ItemCode"))));
                                    }
                                }
                            }
                        }

                        var matrixAttributes = AppLogic.GetMatrixItemAttributes(lineItemRow.ItemCode, Customer.Current.LanguageCode);
                        var matrixDetails = new StringBuilder();

                        matrixAttributes.ForEach(itemAttributes =>
                        {
                            matrixDetails.AppendFormat("&nbsp;&nbsp;{0}:{1}<br />", Security.HtmlEncode(itemAttributes.AttributeValue), Security.HtmlEncode(itemAttributes.AttributeValueDescription));
                        });

                        xmlcartItem.Add(new XElement("MatrixDetails", matrixDetails.ToString()));
                        break;
                    #endregion

                    #region "ITEM_TYPE_KIT"
                    case Interprise.Framework.Base.Shared.Const.ITEM_TYPE_KIT:
                        
                        xmlcartItem.Add(new XElement("ITEM_TYPE", "ITEM_TYPE_KIT"));
                        xmlcartItem.Add(new XElement("KIT_EDIT_IMAGE_ALT", cart.SkinID, AppLogic.GetString("shoppingcart.cs.4", 1, cart.ThisCustomer.LocaleSetting)));

                        string href = InterpriseSuiteEcommerceCommon.InterpriseHelper.MakeItemLink(item.ItemCode) + "?kcid={0}".FormatWith(item.Id.ToString());
                        xmlcartItem.Add(new XElement("KIT_EDIT_HREF", href));

                        xmlcartItem.Add(new XElement("PRODUCT_HREF", producthref));
                        xmlcartItem.Add(new XElement("KIT_SHOWDETAILSTEXT", AppLogic.GetString("mobile.wishlist.aspx.2", cart.SkinID, cart.ThisCustomer.LocaleSetting)));
                        xmlcartItem.Add(new XElement("KIT_HIDEDETAILSTEXT", AppLogic.GetString("mobile.wishlist.aspx.3", cart.SkinID, cart.ThisCustomer.LocaleSetting)));

                        var kitDetailRelation = cart.SalesOrderDataset.GetRelation(
                                                        cart.SalesOrderDataset.CustomerSalesOrderDetailView,
                                                        cart.SalesOrderDataset.CustomerItemKitDetailView
                        );

                        var kitItems = new XElement("KIT_ITEMS");
                        var lineItemRows = lineItemRow.GetChildRows(kitDetailRelation);

                        lineItemRows.ForEach(kitItemDetail =>
                        {
                            var kitDetail = ((SalesOrderDatasetGateway.CustomerItemKitDetailViewRow)kitItemDetail);
                            var kitItem = new XElement("KITITEM");
                            kitItem.Add(new XElement("QTY", Localization.ParseLocaleDecimal(kitDetail.QuantityPerKit, cart.ThisCustomer.LocaleSetting)));
                            kitItem.Add(new XElement("DESCRIPTION", Security.HtmlEncode(kitDetail.ItemDescription)));
                            kitItems.Add(kitItem);
                        });
                       
                        xmlcartItem.Add(kitItems);

                        break;
                    #endregion

                    #region  "STOCK"
                    default:
                        xmlcartItem.Add(new XElement("ITEM_TYPE", "ITEM_TYPE_STOCK"));
                        //xml already processed above.
                        xmlcartItem.Add(new XElement("PRODUCT_HREF", producthref));
                        break;
                    #endregion
                }

                xmlcartItem.Add(new XElement("SHOWSTOCKHINTS", showStockHints));
                if (showStockHints)
                {
                    if (showShipDateInCart)
                    {
                        string allocatedQty = Localization.ParseLocaleDecimal(item.m_AllocatedQty, cart.ThisCustomer.LocaleSetting);
                        xmlcartItem.Add(new XElement("ALLOCATEDQTY", allocatedQty));
                        if (item.m_AllocatedQty > 0)
                        {
                            xmlcartItem.Add(new XElement("SHIPPING_TEXT", AppLogic.GetString("mobile.shoppingcart.cs.2", cart.SkinID, cart.ThisCustomer.LocaleSetting)));
                        }

                        var reserveCol = cart.GetReservation(item.ItemCode);
                        if (reserveCol.Count > 0) xmlcartItem.Add(new XElement("SHIPPINGON_TEXT", AppLogic.GetString("mobile.shoppingcart.cs.3", cart.SkinID, cart.ThisCustomer.LocaleSetting)));

                        xmlcartItem.Add(new XElement("RESERVATION_COUNT", reserveCol.Count));
                        var reservationItems = reserveCol
                                .Select(r => new XElement("RESERVATIONITEM",
                                        new XElement("RESERVE_ITEMCODE", r.ItemCode),
                                        new XElement("RESERVE_SHIPDATE", r.ShipDate.ToShortDateString()),
                                        new XElement("RESERVE_QTY", Localization.ParseLocaleDecimal(r.QtyReserved, cart.ThisCustomer.LocaleSetting))));
                        xmlcartItem.Add(reservationItems);
                    }
                }

                #region "Unit Measure"

                xmlcartItem.Add(new XElement("NOT_HIDE_UNIT_MEASURE", !hideUnitMeasure));
                if (!hideUnitMeasure)
                {
                    xmlcartItem.Add(new XElement("UNITMEASUREDESCRIPTION", AppLogic.GetUnitMeassureDescription(item.UnitMeasureCode).ToHtmlEncode()));
                }

                #endregion

                xmlcartItem.Add(new XElement("INPUTQUANTITYVALUE", Localization.ParseLocaleDecimal(item.m_Quantity, cart.ThisCustomer.LocaleSetting)));
                xmlcartItem.Add(new XElement("HASCOUPON", hasCoupon));
                if (hasCoupon)
                {
                    // Sales Price 
                    xmlcartItem.Add(new XElement("COUPON_SALESPRICERATE", cart.ThisCustomer.FormatBasedOnMyCurrency(lineItemRow.SalesPriceRate)));
                    xmlcartItem.Add(new XElement("COUPON_DISCOUNTRATE", cart.ThisCustomer.FormatBasedOnMyCurrency(lineItemRow.CouponDiscountRate)));
                }

                xmlcartItem.Add(new XElement("VATENABLED", varEnabled));

                // Extended Price
                decimal extPriceRate = item.Price;
                if (varEnabled)
                {
                    decimal vatComputed = item.TaxRate;

                    string vatSettingText = AppLogic.GetString("showproduct.aspx.37", cart.ThisCustomer.SkinID, cart.ThisCustomer.LocaleSetting);
                    if (cart.ThisCustomer.VATSettingReconciled == VatDefaultSetting.Inclusive)
                    {
                        extPriceRate += vatComputed;
                        vatSettingText = AppLogic.GetString("showproduct.aspx.38", cart.ThisCustomer.SkinID, cart.ThisCustomer.LocaleSetting);
                        xmlcartItem.Add(new XElement("VATAMOUNT_TEXT", AppLogic.GetString("showproduct.aspx.41", cart.ThisCustomer.SkinID, cart.ThisCustomer.LocaleSetting)));
                        xmlcartItem.Add(new XElement("VATAMOUNT_VALUE", cart.ThisCustomer.FormatBasedOnMyCurrency(vatComputed)));
                    }

                    xmlcartItem.Add(new XElement("PRICEFORMATTED", cart.ThisCustomer.FormatBasedOnMyCurrency(extPriceRate)));
                    xmlcartItem.Add(new XElement("VATSETTING_TEXT", vatSettingText));
                }
                else
                {
                    xmlcartItem.Add(new XElement("PRICEFORMATTED", InterpriseHelper.FormatCurrencyForCustomer(extPriceRate, cart.ThisCustomer.CurrencyCode)));
                }
            }

            decimal subTotal = cart.SalesOrderDataset.CustomerSalesOrderView[0].SubTotalRate;
            decimal tax = cart.SalesOrderDataset.CustomerSalesOrderView[0].TaxRate;
            decimal dueTotal = cart.SalesOrderDataset.CustomerSalesOrderView[0].TotalRate;
            decimal balance = cart.SalesOrderDataset.CustomerSalesOrderView[0].BalanceRate;
            decimal discount = cart.SalesOrderDataset.CustomerSalesOrderView[0].CouponDiscountRate;
            decimal freight = cart.SalesOrderDataset.CustomerSalesOrderView[0].FreightRate;
            string currencyCode = cart.ThisCustomer.CurrencyCode;

            if (varEnabled)
            {
                if (cart.ThisCustomer.VATSettingReconciled == VatDefaultSetting.Inclusive)
                {
                    subTotal += tax;
                }
                else
                {
                    dueTotal -= tax;
                    balance -= tax;
                }
            }

            root.Add(new XElement("SUBTOTAL_TEXT", AppLogic.GetString("shoppingcart.cs.27", cart.SkinID, cart.ThisCustomer.LocaleSetting)));
            root.Add(new XElement("SUBTOTAL_VALUE", InterpriseHelper.FormatCurrencyForCustomer(subTotal, currencyCode)));

            root.Add(new XElement("TOTAL_CAPTION", AppLogic.GetString("shoppingcart.cs.11", cart.SkinID, cart.ThisCustomer.LocaleSetting)));
            root.Add(new XElement("TOTAL_VALUE", InterpriseHelper.FormatCurrencyForCustomer(balance, currencyCode)));

            string freightCaption = AppLogic.GetString("shoppingcart.aspx.10", cart.SkinID, cart.ThisCustomer.LocaleSetting);
            if (varEnabled)
            {
                if (cart.ThisCustomer.VATSettingReconciled == VatDefaultSetting.Inclusive)
                {
                    freightCaption += " " + AppLogic.GetString("showproduct.aspx.38", cart.ThisCustomer.SkinID, cart.ThisCustomer.LocaleSetting);
                }
                else
                {
                    freightCaption += " " + AppLogic.GetString("showproduct.aspx.37", cart.ThisCustomer.SkinID, cart.ThisCustomer.LocaleSetting);
                }
            }
            root.Add(new XElement("FREIGHT_CAPTION", freightCaption));

            bool hasShippableComponents = cart.HasShippableComponents();
            string frieghtValue = string.Empty;
            if (hasShippableComponents)
            {
                bool couponIncludesFreeShipping = cart.CouponIncludesFreeShipping();
                bool isFreeShippingThesholdEnabled = InterpriseHelper.IsFreeShippingThresholdEnabled(subTotal);
                bool isShippingFreeMethodList = InterpriseHelper.ShippingMethodCodeBelongsToFreeShippingMethodList(cart.SalesOrderDataset.CustomerSalesOrderView[0].ShippingMethodCode);

                if (couponIncludesFreeShipping || (isFreeShippingThesholdEnabled && isShippingFreeMethodList))
                {
                    frieghtValue = AppLogic.GetString("shoppingcart.aspx.13", cart.SkinID, cart.ThisCustomer.LocaleSetting);
                }
                else
                {
                    frieghtValue = InterpriseHelper.FormatCurrencyForCustomer(freight, currencyCode);
                }
            }
            else
            {
                frieghtValue = AppLogic.GetString("shoppingcart.aspx.13", cart.SkinID, cart.ThisCustomer.LocaleSetting);
            }
            root.Add(new XElement("FREIGHT_VALUE", frieghtValue));

            string taxCaption = AppLogic.GetString("shoppingcart.aspx.11", cart.SkinID, cart.ThisCustomer.LocaleSetting);
            if (varEnabled)
            {
                taxCaption = AppLogic.GetString("shoppingcart.aspx.15", cart.SkinID, cart.ThisCustomer.LocaleSetting);
            }
            root.Add(new XElement("TAX_CAPTION", taxCaption));
            root.Add(new XElement("TAX_VALUE", InterpriseHelper.FormatCurrencyForCustomer(tax, currencyCode)));

            if (hasCoupon)
            {
                root.Add(new XElement("DUETOTAL_CAPTION", AppLogic.GetString("shoppingcart.cs.1008", cart.SkinID, cart.ThisCustomer.LocaleSetting)));
                root.Add(new XElement("DUETOTAL_VALUE", InterpriseHelper.FormatCurrencyForCustomer(dueTotal, currencyCode)));

                root.Add(new XElement("DISCOUNT_CAPTION", AppLogic.GetString("shoppingcart.cs.38", cart.SkinID, cart.ThisCustomer.LocaleSetting)));
                root.Add(new XElement("DISCOUNT_VALUE", InterpriseHelper.FormatCurrencyForCustomer(discount, currencyCode)));
            }

            string html = new XmlPackage2("page.checkoutpayment_template.xml.config", root).TransformString();
            output.Append(html);
        }

        private void RenderSummary(InterpriseShoppingCart cart, HtmlTextWriter writer)
        {
            // The values
            decimal subTotal = cart.SalesOrderDataset.CustomerSalesOrderView[0].SubTotalRate;
            decimal freight = cart.SalesOrderDataset.CustomerSalesOrderView[0].FreightRate;
            decimal tax = cart.SalesOrderDataset.CustomerSalesOrderView[0].TaxRate;
            decimal discount = cart.SalesOrderDataset.CustomerSalesOrderView[0].CouponDiscountRate;
            decimal dueTotal = cart.SalesOrderDataset.CustomerSalesOrderView[0].TotalRate;
            decimal balance = cart.SalesOrderDataset.CustomerSalesOrderView[0].BalanceRate;

            if (AppLogic.AppConfigBool("VAT.Enabled"))
            {
                if (cart.ThisCustomer.VATSettingReconciled == VatDefaultSetting.Inclusive)
                {
                    subTotal += tax;

                    decimal freightTax = cart.SalesOrderDataset.CustomerSalesOrderView[0].FreightTaxRate;

                    subTotal -= freightTax;
                    freight += freightTax;
                }
            }

            string currencyCode = cart.ThisCustomer.CurrencyCode;

            // Captions
            string subTotalCaption = AppLogic.GetString("shoppingcart.cs.27", cart.SkinID, cart.ThisCustomer.LocaleSetting);
            string freightCaption = AppLogic.GetString("shoppingcart.aspx.10", cart.SkinID, cart.ThisCustomer.LocaleSetting);

            if (AppLogic.AppConfigBool("VAT.Enabled"))
            {
                if (cart.ThisCustomer.VATSettingReconciled == VatDefaultSetting.Inclusive)
                {
                    freightCaption += "&nbsp;" + AppLogic.GetString("showproduct.aspx.38", cart.ThisCustomer.SkinID, cart.ThisCustomer.LocaleSetting);
                }
                else
                {
                    freightCaption += "&nbsp;" + AppLogic.GetString("showproduct.aspx.37", cart.ThisCustomer.SkinID, cart.ThisCustomer.LocaleSetting);
                }
            }

            string taxCaption = AppLogic.GetString("shoppingcart.aspx.11", cart.SkinID, cart.ThisCustomer.LocaleSetting);
            if (AppLogic.AppConfigBool("VAT.Enabled"))
            {
                taxCaption = AppLogic.GetString("shoppingcart.aspx.15", cart.SkinID, cart.ThisCustomer.LocaleSetting);
            }

            string discountCaption = AppLogic.GetString("shoppingcart.cs.38", cart.SkinID, cart.ThisCustomer.LocaleSetting);
            string totalCaption = AppLogic.GetString("shoppingcart.cs.11", cart.SkinID, cart.ThisCustomer.LocaleSetting);

            Panel divSummary = new Panel();
            divSummary.Attributes.Add("align", "right");

            Table tblSummary = new Table();
            tblSummary.Width = Unit.Percentage(100);

            // SubTotal Row
            TableRow rowSubTotal = new TableRow();

            TableCell cellSubTotalCaption = new TableCell();
            cellSubTotalCaption.Attributes.Add("align", "right");
            cellSubTotalCaption.Width = Unit.Percentage(100);
            cellSubTotalCaption.Controls.Add(new LiteralControl(string.Format("{0}&#160;", subTotalCaption)));
            rowSubTotal.Cells.Add(cellSubTotalCaption);

            TableCell cellSubTotalValue = new TableCell();
            cellSubTotalValue.Attributes.Add("align", "right");
            cellSubTotalValue.Attributes.Add("valign", "middle");
            cellSubTotalValue.Controls.Add(new LiteralControl(string.Format("<nobr>{0}</nobr>", InterpriseHelper.FormatCurrencyForCustomer(subTotal, currencyCode))));
            rowSubTotal.Cells.Add(cellSubTotalValue);

            tblSummary.Rows.Add(rowSubTotal);

            // Freight Row
            TableRow rowFreight = new TableRow();

            TableCell cellFreightCaption = new TableCell();
            cellFreightCaption.Attributes.Add("align", "right");
            cellFreightCaption.Width = Unit.Percentage(100);
            cellFreightCaption.Controls.Add(new LiteralControl(string.Format("{0}&#160;", freightCaption)));
            rowFreight.Cells.Add(cellFreightCaption);

            TableCell cellFreightValue = new TableCell();
            cellFreightValue.Attributes.Add("align", "right");
            cellFreightValue.Attributes.Add("valign", "middle");

            if (cart.HasShippableComponents())
            {
                if (cart.CouponIncludesFreeShipping())
                {
                    cellFreightValue.Controls.Add(new LiteralControl(AppLogic.GetString("shoppingcart.aspx.13", cart.SkinID, cart.ThisCustomer.LocaleSetting)));
                }
                else if (InterpriseHelper.IsFreeShippingThresholdEnabled(subTotal) &&
                    InterpriseHelper.ShippingMethodCodeBelongsToFreeShippingMethodList(cart.SalesOrderDataset.CustomerSalesOrderView[0].ShippingMethodCode))
                {
                    cellFreightValue.Controls.Add(new LiteralControl(AppLogic.GetString("shoppingcart.aspx.13", cart.SkinID, cart.ThisCustomer.LocaleSetting)));
                }
                else
                {
                    cellFreightValue.Controls.Add(new LiteralControl(string.Format("<nobr>{0}</nobr>", InterpriseHelper.FormatCurrencyForCustomer(freight, currencyCode))));
                }
            }
            else
            {
                cellFreightValue.Controls.Add(new LiteralControl(AppLogic.GetString("shoppingcart.aspx.13", cart.SkinID, cart.ThisCustomer.LocaleSetting)));
            }
            rowFreight.Cells.Add(cellFreightValue);

            tblSummary.Rows.Add(rowFreight);

            if (AppLogic.AppConfigBool("VAT.Enabled") &&
                cart.ThisCustomer.VATSettingReconciled == VatDefaultSetting.Inclusive)
            {
                // don't display the tax
            }
            else
            {
                // Tax Row
                TableRow rowTax = new TableRow();

                TableCell cellTaxCaption = new TableCell();
                cellTaxCaption.Attributes.Add("align", "right");
                cellTaxCaption.Width = Unit.Percentage(100);
                cellTaxCaption.Controls.Add(new LiteralControl(string.Format("{0}&#160;", taxCaption)));
                rowTax.Cells.Add(cellTaxCaption);

                TableCell cellTaxValue = new TableCell();
                cellTaxValue.Attributes.Add("align", "right");
                cellTaxValue.Attributes.Add("valign", "middle");
                cellTaxValue.Controls.Add(new LiteralControl(string.Format("<nobr>{0}</nobr>", InterpriseHelper.FormatCurrencyForCustomer(tax, currencyCode))));
                rowTax.Cells.Add(cellTaxValue);

                tblSummary.Rows.Add(rowTax);
            }

            bool hasCoupon =
                !cart.SalesOrderDataset.CustomerSalesOrderView[0].IsCouponIDNull() && !string.IsNullOrEmpty(cart.SalesOrderDataset.CustomerSalesOrderView[0].CouponID);

            if (hasCoupon)
            {
                // Divider Row
                TableRow rowDueTotalDivider = new TableRow();

                // filler table cell
                rowDueTotalDivider.Cells.Add(new TableCell());

                TableCell cellDueTotalDivider = new TableCell();
                cellDueTotalDivider.Controls.Add(new LiteralControl("<hr />"));
                rowDueTotalDivider.Controls.Add(cellDueTotalDivider);

                tblSummary.Rows.Add(rowDueTotalDivider);

                // Due Total Row
                TableRow rowDueTotal = new TableRow();

                TableCell cellDueTotalCaption = new TableCell();
                cellDueTotalCaption.Attributes.Add("align", "right");
                cellDueTotalCaption.Width = Unit.Percentage(100);
                rowDueTotal.Cells.Add(cellDueTotalCaption);

                TableCell cellDueTotalValue = new TableCell();
                cellDueTotalValue.Attributes.Add("align", "right");
                cellDueTotalValue.Attributes.Add("valign", "middle");
                cellDueTotalValue.Controls.Add(new LiteralControl(string.Format("<nobr>{0}</nobr>", InterpriseHelper.FormatCurrencyForCustomer(dueTotal, currencyCode))));
                rowDueTotal.Cells.Add(cellDueTotalValue);

                tblSummary.Rows.Add(rowDueTotal);


                // Coupon Row
                TableRow rowCoupon = new TableRow();

                TableCell cellCouponCaption = new TableCell();
                cellCouponCaption.Attributes.Add("align", "right");
                cellCouponCaption.Width = Unit.Percentage(100);
                cellCouponCaption.Controls.Add(new LiteralControl(string.Format("{0}&#160;", discountCaption)));
                rowCoupon.Cells.Add(cellCouponCaption);

                TableCell cellCouponValue = new TableCell();
                cellCouponValue.Attributes.Add("align", "right");
                cellCouponValue.Attributes.Add("valign", "middle");
                cellCouponValue.Controls.Add(new LiteralControl(string.Format("<nobr>{0}</nobr>", InterpriseHelper.FormatCurrencyForCustomer(discount, currencyCode))));
                rowCoupon.Cells.Add(cellCouponValue);

                tblSummary.Rows.Add(rowCoupon);
            }

            // Divider Row
            TableRow rowTotalDivider = new TableRow();

            // filler table cell
            rowTotalDivider.Cells.Add(new TableCell());

            TableCell cellTotalDivider = new TableCell();
            cellTotalDivider.Controls.Add(new LiteralControl("<hr />"));
            rowTotalDivider.Cells.Add(cellTotalDivider);

            tblSummary.Rows.Add(rowTotalDivider);

            // Total/Balance Row
            TableRow rowTotal = new TableRow();

            TableCell cellTotalCaption = new TableCell();
            cellTotalCaption.Attributes.Add("align", "right");
            cellTotalCaption.Width = Unit.Percentage(100);
            cellTotalCaption.Controls.Add(new LiteralControl(string.Format("{0}&#160;", totalCaption)));
            rowTotal.Cells.Add(cellTotalCaption);

            TableCell cellTotalValue = new TableCell();
            cellTotalValue.Attributes.Add("align", "right");
            cellTotalValue.Attributes.Add("valign", "middle");
            cellTotalValue.Controls.Add(new LiteralControl(string.Format("<nobr>{0}</nobr>", InterpriseHelper.FormatCurrencyForCustomer(balance, currencyCode))));
            rowTotal.Cells.Add(cellTotalValue);

            tblSummary.Rows.Add(rowTotal);

            divSummary.Controls.Add(tblSummary);

            divSummary.RenderControl(writer);
        }
    }
}
